package com.information.manage.MaintenanceRecord.controller;

import com.information.manage.MaintenanceRecord.pojo.zhongmao;
import com.information.manage.MaintenanceRecord.service.zhongmaoService;
import com.information.manage.basic.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/MaintenanceRecord/zhongmao")
public class zhongmaoController {

    @Autowired
    private zhongmaoService zhongmaoService;

    @GetMapping("/selectAll")
    public Result<List<zhongmao>> selectAll() {
        List<zhongmao> records = zhongmaoService.selectAll();
        return Result.ok(records);
    }

    @PostMapping("/add")
    public Result<String> addZhongmao(@RequestBody zhongmao zhongmao) {
        try {
            zhongmaoService.addMaintZhongmao(zhongmao);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error("添加中锚记录出现异常: ", e);
            return Result.fail("添加失败");
        }
    }

    @PutMapping("/update/{zmid}")
    public Result<String> updateZhongmao(@PathVariable("zmid") Integer zmid, @RequestBody zhongmao zhongmao) {
        try {
            zhongmao.setZmid(zmid);
            zhongmaoService.updateMaintZhongmao(zhongmao);
            return Result.ok("更新成功");
        } catch (Exception e) {
            log.error("更新中锚记录出现异常: ", e);
            return Result.fail("更新失败");
        }
    }

    @DeleteMapping("/delete/{zmid}")
    public Result<String> deleteZhongmao(@PathVariable("zmid") Integer zmid) {
        try {
            zhongmaoService.logicDeleteMaintZhongmao(zmid);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error("逻辑删除中锚记录出现异常: ", e);
            return Result.fail("删除失败");
        }
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            String fileName = java.net.URLEncoder.encode("中锚记录数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<zhongmao> list = zhongmaoService.selectAll();
            if (list == null || list.isEmpty()) {
                response.getWriter().write("暂无中锚记录数据可供下载");
                return;
            }
            try {
                response.getWriter().write("下载功能尚未实现，请联系管理员");
            } catch (Exception e) {
                response.getWriter().write("下载过程中数据写入出现错误，请联系管理员");
            }
        } catch (IOException e) {
            response.getWriter().write("系统出现异常，下载失败，请稍后再试");
        }
    }
}